package com.tidc.seaserverservice.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tidc.seaservermodel.exception.TidcBadParent;
import com.tidc.seaservermodel.exception.TidcRestException;
import com.tidc.seaservermodel.properties.AliyunProperties;
import com.tidc.seaservermodel.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/10/14 14:52
 * @description：
 * @modified By：
 * @version:
 */
@Component
@Slf4j
public class SendCodeUtil {
    @Resource
    private AliyunProperties aliyunProperties;

    public Map<Object, Object> sendMessage(String phone, int code) throws ClientException, TidcBadParent, TidcRestException {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunProperties.getMessageAccessKeyId(), aliyunProperties.getMessageSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "燎原之海");
        request.putQueryParameter("TemplateCode", aliyunProperties.getMessageTemplateCode());
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        CommonResponse response = client.getCommonResponse(request);
        String data = response.getData();
        JSONObject jsonObject = JSON.parseObject(data);
        Map<Object, Object> map = (Map) jsonObject;
        String resCodeMessage = (String) map.get("Code");
        if (resCodeMessage.equals("OK")) {
            return map;
        }
        if (resCodeMessage.equals("isv.MOBILE_NUMBER_ILLEGAL") || resCodeMessage.equals("isv.DOMESTIC_NUMBER_NOT_SUPPORTED") || resCodeMessage.equals("isv.DAY_LIMIT_CONTROL") || resCodeMessage.equals("isp.OUT_OF_SERVICE")) {
            log.error("阿里云短信服务参数出错 map {}", map);
            throw new TidcBadParent("手机号错误");
        } else {
            log.error("阿里云短信服务出问题 map {}", map);
            throw new TidcRestException("阿里云出错");
        }
    }
}
